import React from 'react'
import { Form, Input, Button, Message ,Upload,Icon} from 'antd';
const FormItem = Form.Item;
import userApi from '../../../api/user';
import './index.less'
import PanelBox from '../../../components/PanelBox';
import {INTERFACE_CORE_URL} from '../../../api/config';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  if (!isJPG) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJPG && isLt2M;
}


 class UserForm extends React.Component {
  state = {
    loading: false,
    user: [],
    userFrom:{}
  };

  initData = () => {
    this.setState({ loading: true });
    userApi.get('/getAllUserById', {id:"user" }).then((data) => {
      const _data = data.data;
      this.setState({
        loading: false,
        user: _data
      });
    });
  }
  
  handleSubmit = (e) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const result=values.photo.file;
        if(typeof(result) != "undefined"){
          const data=result.response.data;
          values.photo=data.fullPath;
        }
        if(values.id){
          userApi.put('/updateUser', {...values}).then((data) => {
            const result= data.data;
            if(result.code == 0){
              Message.success('修改成功！');
            }else{
              Message.error(result.message);
            }
          });
        }else{
          message.error('网络错误，请稍后再试');
        }
      }
    });
  }
  componentDidMount = () =>{
    this.initData();
  }
  showPayModal =()=>{
    this.props.showPayModal();
  }
  handleFormChange = (changedFields) => {
    this.setState({
      userFrom: { ...this.state.userFrom, ...changedFields },
    });
  }
  handleImageChange = (info) => {
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      if(info.file.response){
        this.setState({ imageUrl:info.file.response.data.fullPath + '?process=image/resize,width_150,height_150'})
      }
      
    }
  }
  render() { 
   const { getFieldDecorator } = this.props.form;
   
   const imageUrl = this.state.imageUrl;
    const formItemLayout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 7 },
    };
    let imgStyle={};
    if(this.state.user){
      this.state.user.widthImg=this.state.user.photo+"?process=image/resize,width_150,height_150";
      let url="";
      if(imageUrl){
        url=imageUrl;
      }else{
        url=this.state.user.widthImg;
      }
      imgStyle={background:"url("+url+") center center no-repeat"};
    }else{
      imgStyle={background:"url("+imageUrl+") center center no-repeat"};
    }
  
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 15,
          offset: 9,
        },
        sm: {
          span: 15,
          offset: 9,
        },
      },
    };
    return (
          <Form onSubmit={this.handleSubmit}>
              {getFieldDecorator('id', {
                initialValue:this.state.user?this.state.user.id:''
              })(
                <input type="hidden" />
              )}
             <FormItem
               {...formItemLayout}
                label="用户头像"
                hasFeedback
              >
                {getFieldDecorator('photo', {
                  rules: [{
                    required: true, message: '请上传一个头像图片!',
                  }],
                  initialValue:this.state.user?this.state.user.photo:''
                })(
                  <Upload
                    className="avatar-uploader"
                    name="file"
                    showUploadList={false}
                    action={INTERFACE_CORE_URL+"/upload"}
                    beforeUpload={beforeUpload}
                    onChange={this.handleImageChange}
                  >
                    {
                      this.state.user ? 
                        (imageUrl || this.state.user.photo) ?
                        <div style={imgStyle} className="avatar" ></div> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                        : 
                        (imageUrl) ?
                        <div style={imgStyle} className="avatar" ></div> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                    }
                  </Upload>
                )}
              </FormItem>
              <FormItem
                  {...formItemLayout}
                  label="姓名"
                >
                  <span className="ant-form-text">{this.state.user.name}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="工号"
                >
                  <span className="ant-form-text">{this.state.user.no}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="登录名"
                >
                  <span className="ant-form-text">{this.state.user.loginName}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="联系手机"
                >
                  <span className="ant-form-text">{this.state.user.phone}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="联系邮箱"
                >
                  <span className="ant-form-text">{this.state.user.email}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="登录IP"
                >
                  <span className="ant-form-text">{this.state.user.loginIp}</span>
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="更新时间"
                >
                  <span className="ant-form-text">{this.state.user.updateDate}</span>
                </FormItem>
              <FormItem {...tailFormItemLayout}>
                <Button loading={this.state.loading} type="primary" htmlType="submit" size="large" >保存</Button>
              </FormItem>
            </Form>
         
    );
  }
}
const UsershowForm = Form.create({})(UserForm);

export default class showUser extends React.Component {
  render() {
    return (
      <PanelBox>
        <div className="password-content">
          <UsershowForm/>
        </div>
      </PanelBox >
      
    )
  }

}